package com.corn.flink.lesson1;

import cn.hutool.core.io.FileUtil;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.client.program.StreamContextEnvironment;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2023/2/16 11:26
 */

public class FlinkStreamWordCountDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamContextEnvironment.getExecutionEnvironment();
        // 2. 读取数据
        String filePath = FileUtil.getAbsolutePath("classpath:input/wordcount.txt");
        DataStreamSource<String> dataStreamSource = env.readTextFile(filePath);

        // flat map
        SingleOutputStreamOperator<Tuple2<String, Long>> mappedDs = dataStreamSource.flatMap((String line, Collector<Tuple2<String, Long>> collector) -> {
            String[] words = line.split(" ");
            Arrays.stream(words).forEach(w -> {
                collector.collect(Tuple2.of(w, 1L));
            });
        }).returns(Types.TUPLE(Types.STRING, Types.LONG));

        SingleOutputStreamOperator<Tuple2<String, Long>> result = mappedDs.keyBy((k) -> k.f0).sum(1);
        result.print();
        env.execute();
    }
}
